﻿/*************************************************************************
Sofia Public Transportation Client for WP7
    Copyright (C) 2011  Author: Tosho Toshev

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Xml;
using System.Windows.Navigation;


/*-----------------------------------------------------------------------------------------------------------*/
/*
 * This is the binded list page!
 * This page is filled with a list of XML specific data items on OnNavigatedTo event.
 * The code is under the free GNU License v3.
 */
/*-----------------------------------------------------------------------------------------------------------*/

namespace SofiaSKGTwp7
{
    public partial class BindedList : PhoneApplicationPage
    {
        private int  TRtype = -1;
        private int  ActiveParam = 0;

        private bool enTrams   = false;
        private bool enBus     = false;
        private bool enTrolley = false;
        private bool enTrType  = false;
        private bool enLine    = false;
        private int  tmpOffset = 0;

        private XmlReader datReader;

        //Constructor logic
        public BindedList()
        {
            InitializeComponent();

            listBox1.FontSize = 30;

            try
            {
                datReader = XmlReader.Create("SKGT.xml");
            }
            catch (XmlException e) 
            {
                MessageBox.Show(e.Message);
            }

        }


//A Method that populates the Listbox with values according to the ActiveParam===================================================//
//THIS IS THE OLD PARSING ROUTINE - THE NEW 7.1 tools have LINQ XML browsing - NEEDS REFACTORING
        private bool PopulateList(int ActiveParam)
        {
            XmlReader tmpReader = null;

            bool Result = false;
            listBox1.Items.Clear();

            while(datReader.Read()) //THE WP7.0 STUPID PARSING ROUTINE
            {
                if (datReader.IsStartElement())
                {
                    switch (ActiveParam)
                    {
                        case 1:             //Parse the transportation type=======================================================
                                if (datReader.Name.ToLower() == "type")
                                {
                                    listBox1.Items.Add(datReader.GetAttribute("Name"));
                                }

                            break;
                        case 2:             //Parse the line number===============================================================
                                if ((datReader.Name.ToLower() == "type")&&
                                    (datReader.GetAttribute("id") == "0"))
                                {
                                    enTrams   = true;
                                    enBus     = false;
                                    enTrolley = false;
                                }
                                else if ((datReader.Name.ToLower() == "type") &&
                                    (datReader.GetAttribute("id") == "1"))
                                {
                                    enTrams   = false;
                                    enBus     = true;
                                    enTrolley = false;
                                }
                                else if ((datReader.Name.ToLower() == "type") &&
                                    (datReader.GetAttribute("id") == "2"))
                                {
                                    enTrams   = false;
                                    enBus     = false;
                                    enTrolley = true;
                                }


                                if ((datReader.Name.ToLower() == "line")&&(enTrams) && (TRtype == 0))
                                {
                                    listBox1.Items.Add(datReader.GetAttribute("id"));
                                }

                                if ((datReader.Name.ToLower() == "line") && (enBus) && (TRtype == 1))
                                {
                                    listBox1.Items.Add(datReader.GetAttribute("id"));
                                }

                                if ((datReader.Name.ToLower() == "line") && (enTrolley) && (TRtype == 2))
                                {
                                    listBox1.Items.Add(datReader.GetAttribute("id"));
                                }

                            break;
                        case 3:         //Parse the direction=====================================================================
                                if (datReader.Name.ToLower() == "type")
                                {
                                    if (int.Parse(datReader.GetAttribute("id")) == (Application.Current as App).TRID)
                                    {
                                        enTrType = true;
                                    }
                                    else
                                    {
                                        enTrType = false;
                                    }
                                }

                                if ((datReader.Name.ToLower() == "line") && (enTrType) &&
                                    ((Application.Current as App).LNAME == datReader.GetAttribute("id")))
                                {
                                    enLine = true;
                                }

                                if ((datReader.Name.ToLower() == "direction") &&(enLine))
                                {
                                    string test = datReader.GetAttribute("name");
                                    listBox1.Items.Add(test);
                                    tmpOffset++;

                                    if (tmpOffset == 2)
                                    {
                                        enLine   = false;
                                        enTrType = false;
                                    }
                                }

                            break;
                        case 4:         //Parse the bus stops=======================================================================
                            
                                listBox1.FontSize = 26;

                                if ((datReader.Name.ToLower() == "type") &&
                                (int.Parse(datReader.GetAttribute("id")) == (Application.Current as App).TRID))
                                {
                                    enTrType = true;
                                }
                                else if ((datReader.Name.ToLower() == "type") &&
                                (int.Parse(datReader.GetAttribute("id")) != (Application.Current as App).TRID))
                                {
                                    enTrType = false;
                                }

                                if ((datReader.Name.ToLower() == "line") &&(enTrType)&&
                                (datReader.GetAttribute("id") == (Application.Current as App).LNAME))
                                {
                                    enLine = true;
                                }

                                if((datReader.Name.ToLower() == "direction") &&(enLine)&&
                                (int.Parse(datReader.GetAttribute("id")) == (Application.Current as App).DIRID))
                                {
                                    enLine = false;

                                    tmpReader = datReader.ReadSubtree();

                                    while (tmpReader.Read())
                                    {
                                        if (tmpReader.Name.ToLower() == "stop")
                                        {
                                            listBox1.Items.Add(tmpReader.ReadElementContentAsString());
                                        }
                                    }
                                }

                            break;
                    } //END SWITCH                                             
                } //END IF
            } //END WHILE


            return Result;
        }


//OnNavigated Method=============================================================================================
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            IDictionary<string, string> parameters = this.NavigationContext.QueryString;
            ActiveParam = int.Parse(parameters["Active"]);

            TRtype = (Application.Current as App).TRID;
           

            PopulateList(ActiveParam);
            base.OnNavigatedTo(e);
        }

        private void listBox1_ManipulationStarted(object sender, ManipulationStartedEventArgs e)
        {

        }

        private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            switch (ActiveParam)
            {
                case 1:
                       (Application.Current as App).TRID = listBox1.SelectedIndex;
                       if (listBox1.SelectedItem != null)
                            (Application.Current as App).TRNAME = listBox1.SelectedItem.ToString();

                        break;
                case 2: 
                        (Application.Current as App).LID = listBox1.SelectedIndex;
                        if (listBox1.SelectedItem != null)
                            (Application.Current as App).LNAME = listBox1.SelectedItem.ToString();

                        break;
                case 3:
                        (Application.Current as App).DIRID = listBox1.SelectedIndex;
                        if (listBox1.SelectedItem != null)
                            (Application.Current as App).DIRNAME = listBox1.SelectedItem.ToString();

                        break;
                case 4:          //stop selection
                        int stopID   = 0;
                        int startPos = 0;
                        int endPos   = 0;
                        string str = "";

                        if (listBox1.SelectedItem != null)
                        {
                            startPos = listBox1.SelectedItem.ToString().IndexOf('(');
                            endPos   = listBox1.SelectedItem.ToString().IndexOf(')');
                            str      = listBox1.SelectedItem.ToString().Substring(startPos+1, ((endPos - 1) - startPos));
                            stopID   = int.Parse(str);

                            (Application.Current as App).STID = stopID;

                            (Application.Current as App).STNAME = listBox1.SelectedItem.ToString();
                        }
                        
                        break;
            }

            string arguments = String.Format("?Active={0}", ActiveParam);

            NavigationService.Navigate(new Uri("/MainPage.xaml" + arguments, UriKind.Relative));
        }
    }
}